import { createContext, useState, useContext, useEffect, type ReactNode } from 'react';

// 定义用户数据和认证上下文的类型
interface User {
  userId: number;
  username: string;
  email: string;
  avatar: string;
  vipLevel: number;
  vipExpireTime: string | null;
}

interface AuthContextType {
  isAuthenticated: boolean;
  user: User | null;
  token: string | null;
  login: (userData: User, token: string) => void;
  logout: () => void;
  isLoading: boolean;
}

// 创建上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 创建 AuthProvider 组件
export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(localStorage.getItem('token'));
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const checkUser = async () => {
      if (token) {
        try {
          // 不再信任localStorage，而是从服务器获取最新用户信息
          const response = await fetch('/api/auth/profile', { // 修正接口地址
            headers: {
              'Authorization': `Bearer ${token}`,
            },
          });

          if (response.ok) {
            const data = await response.json();
            if (data.code === 200) {
              // 更新状态和本地缓存
              setUser(data.data);
              localStorage.setItem('user', JSON.stringify(data.data));
            } else {
              // token有效但获取信息失败，可能权限问题，登出
              logout();
            }
          } else {
            // token 无效或过期，登出
            logout();
          }
        } catch (error) {
          console.error('获取用户信息失败', error);
          logout(); // 网络错误等异常，也登出
        }
      }
      setIsLoading(false);
    };
    checkUser();
  }, [token]); // 依赖 token，当 token 变化时（登录/登出）会重新执行

  const login = async (userData: User, newToken: string) => {
    localStorage.setItem('token', newToken);
    localStorage.setItem('user', JSON.stringify(userData));
    setToken(newToken);
    setUser(userData);
  };

  const logout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setToken(null);
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ isAuthenticated: !!token, user, token, login, logout, isLoading }}>
      {children}
    </AuthContext.Provider>
  );
};

// 创建一个自定义 Hook 以方便使用 AuthContext
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}; 